package at.jaki.ubb.crawling.stlib.dataFinder;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import at.jaki.ubb.crawling.api.DataFinder;
import at.jaki.ubb.crawling.model.DataFinderResult;
import at.jaki.ubb.crawling.model.RawData;
import at.jaki.ubb.crawling.model.Target;

/**
 * A simple http data finder. Requires a {@link Target} will String value. This
 * value has to be the full URL of the target website.
 * 
 * Will return the received response as {@link RawData} with generic type
 * String. <br/>
 * <strong>type= url</strong>
 * 
 * @deprecated use {@link SimpleHttpClient}
 * 
 * @author Attila Jakabfi
 * 
 */
@Deprecated
public class SimpleHttpDataFinder implements DataFinder<String, String, String> {

	/**
	 * will accept {@link Target}s of this type
	 */
	public static final String INPUT_TYPE = "simple-url";
	/**
	 * will create {@link RawData} of this type
	 */
	public static String RESULT_TYPE = "webPage";

	public SimpleHttpDataFinder() {
	}

	@Override
	public DataFinderResult<String, String> findData(Target<String> t) {

		String res = callHttp(t.getValue());

		RawData<String> rd = new RawData<String>(t.getValue(), res, new Date(), RESULT_TYPE);

		DataFinderResult<String, String> dataFinderResult = new DataFinderResult<String, String>(Collections.singletonList(rd), null);
		return dataFinderResult;
	}

	protected String callHttp(String urlString) {
		URL url;
		StringBuilder sb = new StringBuilder();

		try {
			url = new URL(urlString);
			URLConnection urlConnection = url.openConnection();
			BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));

			String line;
			while ((line = in.readLine()) != null) {
				sb.append(line);
			}
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return sb.toString();
	}

	@Override
	public void init() {
		// nothing to initialize here...
	}

	@Override
	public List<String> getTypes() {
		return Collections.singletonList(INPUT_TYPE);
	}
}
